# =============================================================================
#'
#' @title Make Simulation Path
#'
#' @description Write GEOtop time series
#'
#' @details This function writes a GEOtop time series such as a meteo file or 
#' a result file. Data is sorted ascending by the "Date" column.
#'
#' @param data Data frame that contains the data to be written as a time series.
#' it must contain a column of type POSIXct named "Date". All other columns 
#' must be of type numeric.
#' @param outfile Full path to the file that should be written.
#' @param round Optional rounding applied to all columns. This can be 0-6 digits
#' with the default of -1 indicating no rounding.
#' @param comment Optional comment to be included in the beginning lines of file.
#' @param env List that passes a number of default settings.
#' @export
#' @return Returns the path to the simulation directory made.   
#' @examples
#' TimeSeriesWrite(meteo, "./data/meteo0001.txt")
#'
#' @author Stephan Gruber <stephan.gruber@@carleton.ca>
#'
# =============================================================================
SimulationPathMake <- function(epath, snumber, env = SetEnv()) {
  #only works on unix/linux/mac
  if (.Platform$OS.type != "unix") {
  	stop("SimulationPathMake only works on Unix, Linux, Mac OSX.")
  }
  	
  #simulation directory
  snumber <- round(snumber, 0)
  spath   <- file.path(epath,formatC(snumber, width = env$digitsd, flag = "0"),
                       fsep = .Platform$file.sep)
  dir.create(spath, showWarnings = TRUE, recursive = FALSE) 
  
  #subdirectories
  for (dir in env$simdirs) {
  	path <- file.path(spath, dir, fsep = .Platform$file.sep)
  	dir.create(path, showWarnings = TRUE, recursive = FALSE) 
  }
  
  #copy parameter file
  par.master <- file.path(epath, env$masterd, env$parfile,
                          fsep = .Platform$file.sep)
  par.target <- file.path(spath, env$parfile,
                          fsep = .Platform$file.sep)
  system(paste("cp", par.master, par.target, sep=" "))
    
  #soft-link all existing input files. Use relative softlinks to enable copying.
  dir.in <- file.path(spath, env$inputd, fsep = .Platform$file.sep)
  dir.wd <- getwd()
  file.list <- list.files(path = dir.in, all.files = FALSE,
                          full.names  = FALSE, recursive    = FALSE,
                          ignore.case = FALSE, include.dirs = TRUE)
  setwd(dir.in)                        
  for (file in file.list) {
  	 "../../_master/meteo meteo"
    target <- file.path("../..", env$masterd, file, fsep = .Platform$file.sep)
    system(paste("ln -sfh", target, file, sep = " "))
  }                        
  setwd(dir.wd)         
  
  return(spath)
}